package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * SL01 使用DOM解析XML
 *
 * @author LILIBO
 * @since 2021-11-27
 */
public class SL01 {

    public static void main(String[] args) {
        try {
            // 获得DOM解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 从DOM工厂获得DOM解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 解析XML文件，获得Document对象
            Document doc = builder.parse("CH02/src/手机收藏信息.xml");
            // 通过标签名称获得节点列表
            NodeList brandList = doc.getElementsByTagName("Brand");
            for (int i = 0; i < brandList.getLength(); i++) {
                // 一个一个的获取节点（Node:节点的意思）
                Node nodeBrand = brandList.item(i);
                short nodeType = nodeBrand.getNodeType();
                System.out.println("节点的类型：" + nodeType);
                if (nodeType == Node.ELEMENT_NODE) {
                    // 将节点转换为元素
                    Element elementBrand = (Element) nodeBrand;
                    String brandName = elementBrand.getAttribute("name");
                    System.out.println("手机品牌：" + brandName);

                    // 获取子节点
                    NodeList childNodes = elementBrand.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node typeNode = childNodes.item(j);
                        short childNodeType = typeNode.getNodeType();
                        System.out.println("\t子节点类型：" + childNodeType);
                        if (childNodeType == Node.ELEMENT_NODE) {
                            Element elementType = (Element) typeNode;
                            String typeName = elementType.getAttribute("name");
                            System.out.println("\t型号；" + typeName);
                        } else if (childNodeType == Node.TEXT_NODE) {
                            System.out.println("\t文本节点内容：" + typeNode.getTextContent());
                        }
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
